// pages/home1/home1.js
const db = wx.cloud.database()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        current_indexNav: 0,
        allRecords: []
    },

    activeMedia: function(e) {
        this.setData({
            current_indexNav: e.currentTarget.dataset.index
        })
        console.log(e.currentTarget.dataset.index)
    },
    jumpToUser:function(e){
        console.log(e.currentTarget.dataset.curuserid)
        wx.setStorage({
          data: e.currentTarget.dataset.curuserid,
          key: 'user',
        })

        wx.navigateTo({
          url: '../user1/user1',
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function() {
      
        var screenWidth = wx.getSystemInfoSync().screenWidth;
        var screenHeight = wx.getSystemInfoSync().screenHeight;
        console.log(screenWidth)
        console.log(screenHeight)

        wx.stopPullDownRefresh() //刷新完成后停止下拉刷新动效
        this.getAllRecords()
        setTimeout(function() {
            wx.hideNavigationBarLoading()
        }, 2000)
    },

    getAllRecords: function() {
        var that = this;
        const media = db.collection("media");
        console.log(media)
        const MAX_LIMIT = 2;
        db.collection('media').count().then(async res => {
            let total = res.total;
            // 计算需分几次取
            const batchTimes = Math.ceil(total / MAX_LIMIT)
                // 承载所有读操作的 promise 的数组
            for (let i = 0; i < batchTimes; i++) {
                await db.collection('media').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get().then(async res => {
                    let new_data = res.data
                    let old_data = that.data.allRecords
                    that.setData({
                        allRecords: old_data.concat(new_data)
                    })
                })
            }
            console.log(that.data.allRecords)
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        wx.showNavigationBarLoading();
        var that = this;
        that.setData({
            current_indexNav: 0,
            allRecords: [] //当前页的一些初始数据
        })
        this.onLoad(); //重新加载onLoad()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})